package com.yh.workbill.ui.home;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.yh.workbill.App;
import com.yh.workbill.R;
import com.yh.workbill.adapter.HomeWorkBillAdapter;
import com.yh.workbill.base.BaseFragment;
import com.yh.workbill.databinding.FragmentHomeBinding;
import com.yh.workbill.db.UserInfo;
import com.yh.workbill.db.UserInfoDao;
import com.yh.workbill.event.AddWorkBillEvent;
import com.yh.workbill.event.EditWorkBillEvent;
import com.yh.workbill.model.WorkBill;
import com.yh.workbill.ui.addworkbill.AddWorkBillActivity;
import com.yh.workbill.ui.editworkbill.EditWorkBillActivity;
import com.yh.workbill.ui.home.mvp.Home_Presenter;
import com.yh.workbill.ui.home.mvp.Home_View;
import com.yh.workbill.ui.search.SearchActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.arch.core.executor.ArchTaskExecutor;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;

import static com.yh.workbill.utils.Config.SP_USER;

public class HomeFragment extends BaseFragment implements Home_View {

    private FragmentHomeBinding binding;
    private HomeViewModel homeViewModel;
    private Home_Presenter presenter;
    private UserInfoDao userInfoDao;
    private HomeWorkBillAdapter adapter;
    private int pageindex = 1, pagenumber = 20;
    private List<WorkBill> workBills = new ArrayList<>();

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_home, container, false);
        return binding.getRoot();
    }

    @Override
    public void initJetPck() {
        homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
        binding.setLifecycleOwner(requireActivity());
    }

    @Override
    public void initSetting() {
        EventBus.getDefault().register(this);
        //requireActivity() 源码做了对空判断
        presenter = new Home_Presenter(this);
        userInfoDao = App.appDataBase.getUserInfoDao();

        binding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageindex = 1;
                getHttpData(true, false);
            }
        });

        binding.refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                getHttpData(false, true);
            }
        });
    }

    @Override
    public void initObserver() {
        requireActivity().getLifecycle().addObserver(presenter);
        homeViewModel.getWorkBilldata().observe(getViewLifecycleOwner(), data -> {
//            for (WorkBill bean : data) {
//                Log.e("TAG", "观察数据是:" + bean.getCompany_name() + " " + bean.getWork_unit() + "\n");
//            }
            adapter.setWorkBills(data);
        });

    }

    @Override
    public void initDefaultMethod() {
        getHttpData(true, false);
    }

    public void getHttpData(boolean isRefresh, boolean isLoadmore) {
        SharedPreferences sp = requireActivity().getSharedPreferences(SP_USER, requireActivity().MODE_PRIVATE);
        String phone = sp.getString("phone", "");
        if (phone != null && !phone.equals("")) {
            ArchTaskExecutor.getIOThreadExecutor().execute(() -> {
                UserInfo singleUserInfo = userInfoDao.getSingleUserInfo(phone);
                String uuid = singleUserInfo.getUuid();
                //加载云单数据
                presenter.getWorkBill(homeViewModel, isRefresh, isLoadmore, uuid, pageindex, pagenumber);
            });
        }
    }

    @Override
    public void initClick() {
        binding.btnAdd.setOnClickListener(v -> goToSearch());
        binding.llSearch.setOnClickListener(v -> {
            Intent i = new Intent(requireActivity(), SearchActivity.class);
            startActivity(i);
        });
    }

    @Override
    public void initData() {
        adapter = new HomeWorkBillAdapter(workBills);
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(requireActivity()));
        binding.recyclerView.setAdapter(adapter);

        adapter.setmOnItemClick((workBill, position) -> {
            Intent i = new Intent(requireActivity(), EditWorkBillActivity.class);
            i.putExtra("workbill", workBill);
            startActivity(i);
        });
    }

    @Override
    public void goToSearch() {
        Intent i = new Intent(requireActivity(), AddWorkBillActivity.class);
        startActivity(i);
    }

    @Override
    public void goToAdd(String... args) {

    }

    @Override
    public void GetDataSuccess() {
        pageindex++;
    }

    @Override
    public void GetDataFail() {
        binding.refreshLayout.finishRefresh();
        binding.refreshLayout.finishLoadMore();
    }

    @Override
    public void refresh() {
        binding.refreshLayout.finishRefresh();//传入false表示刷新失败
    }

    @Override
    public void loadMore() {
        binding.refreshLayout.finishLoadMore();
    }

    @Override
    public void showTasot(String message) {
        if (message != null || !message.equals("")) {
            Toast.makeText(requireActivity(), message, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void showDialog(String content, boolean isCancelable) {
        showLoaddingDialog(content, isCancelable);
    }

    @Override
    public void hideDialog() {
        hideLoaddingDialog();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(AddWorkBillEvent event) {
        /* Do something */
        homeViewModel.addworkBilldatas(0, event.getWorkBill());
//        binding.recyclerView.scrollToPosition(0);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdataWorkBillEvent(EditWorkBillEvent event) {
        WorkBill workBill = event.getWorkBill();
        if (workBill != null) {
            List<WorkBill> value = homeViewModel.getWorkBilldata().getValue();
            for (WorkBill bean : value) {
                if (bean.getUuid().equals(workBill.getUuid())) {
                    bean.setWork_time(workBill.getWork_time());
                    bean.setWork_unit(workBill.getWork_unit());
                    bean.setWork_content(workBill.getWork_content());
                    bean.setWork_car_number(workBill.getWork_car_number());
                    bean.setWork_device(workBill.getWork_device());
                    bean.setWork_use_time(workBill.getWork_use_time());
                    bean.setWork_time_price(workBill.getWork_time_price());
                    double money = workBill.getWork_time_price() / 8 * workBill.getWork_use_time();
                    bean.setWork_money(money);
                    bean.setCompany_uuid(workBill.getCompany_uuid());
                    bean.setCompany_name(workBill.getCompany_name());
                    bean.setCheck(workBill.isCheck());
                    break;
                }
            }
            homeViewModel.update();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDelWorkBillEvent(EditWorkBillEvent event) {
        String uuid = event.getUuid();
        if (!TextUtils.isEmpty(uuid)) {
            List<WorkBill> value = homeViewModel.getWorkBilldata().getValue();
            Iterator<WorkBill> it = value.iterator();
            while (it.hasNext()) {
                WorkBill next = it.next();
                if (next.getUuid().equals(uuid)) {
                    it.remove();
                }
            }
            homeViewModel.update();
        }
    }

}